import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import checker from 'vite-plugin-checker'
import vueSetupExtend from 'vite-plugin-vue-setup-extend'
import path from 'path'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    checker({ vueTsc: true }),
    vueSetupExtend(), // name 取名；<script setup name="componentName">
    vue()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src')
    }
  },
  build: {
    outDir: './dist/lib',
    emptyOutDir: true,
    lib: {
      entry: path.resolve(__dirname, './src/utils/index.ts'),
      name: 'SimpleTools',
      formats: ['es', 'cjs', 'umd'],
      fileName: (format) => {
        if (format === 'es') return 'esm/index.mjs'
        if (format === 'cjs') return 'cjs/index.cjs'
        if (format === 'umd') return 'umd/index.umd.js'
        return `${format}/index.js`
      }
    },
    rollupOptions: {
      // 确保外部化处理那些你不想打包进库的依赖
      external: ['vue', 'vue-router'],
      output: {
        // 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
        globals: {
          vue: 'Vue',
          'vue-router': 'VueRouter'
        },
        // 保留模块结构
        preserveModules: false,
        // 导出模式
        exports: 'named',
        // 分离 sourcemap 到对应目录
        assetFileNames: (assetInfo) => {
          if (assetInfo.name.endsWith('.mjs.map')) return 'esm/[name]'
          if (assetInfo.name.endsWith('.cjs.map')) return 'cjs/[name]'
          if (assetInfo.name.endsWith('.umd.js.map')) return 'umd/[name]'
          return '[name]'
        }
      }
    },
    // 生成 sourcemap
    sourcemap: true,
    // 压缩
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: false
      }
    }
  }
})
